package com.ang.future;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 判断numList中正负数、以及0的个数
 * 并帅选出存在currList中的数字
 *
 * 步骤：
 * 1、实现Callable接口，并指定返回值和具体的实现方法，比如：Callable<String>
 * 2、将该实现类的对象作为参数，使用线程池去执行，如：executorService.submit(Callable);
 * 3、用future接受，并在最后返回结果
 */
public class FutureTest01 {

    //数据集合
    private List<Integer> numList = new ArrayList<>();
    //当前List
    private List<Integer> currList = new ArrayList<>(Arrays.asList(new Integer[]{-5,-4,-3,-2,-1,1,2,3,4,5}));
    private List<Future<Integer>> futureList = new ArrayList<>();
    //正数个数
    private AtomicInteger positiveCount = new AtomicInteger();
    //负数个数
    private AtomicInteger negativeCount = new AtomicInteger();

    //只有一个线程的线程池
    ExecutorService executorService = Executors.newSingleThreadExecutor();

    public static void main(String[] args) {
        FutureTest01 test01 = new FutureTest01();
        try {
            test01.test01();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void test01() throws Exception{
        numList  = this.getNumList();
        for (Integer num : numList) {
            Future<Integer> future = executorService.submit(valid(num));
//            System.out.println(future.get());
            futureList.add(future);
        }

        //开始遍历futureList，future中的任务如果没有返回，是阻塞的
        List<Integer> repeatList = new ArrayList<>();
        for (Future<Integer> future : futureList) {
            try {
                Integer num = future.get();
                System.out.println(num);
                if(currList.contains(num)){
                    repeatList.add(num);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        //打印出重复的元素
        System.out.println("-------------------");
        repeatList.forEach(System.out::print);
    }

    /**
     * 获取数字集合
     * @return
     */
    public List<Integer> getNumList(){
        Integer[] numArr = new Integer[]{-10,-8,-5,-3,-2,-1,0,0,0,1,4,5,3,2,8,9,5,7,6};
        return new ArrayList<>(Arrays.asList(numArr));
    }

    /**
     * 返回一个callable对象，并实现方法：
     *      判断级数和偶数
     */
    public Callable<Integer> valid(int num){
        return ()->{
            if(num > 0){
                //正数
                Thread.sleep(1000);
                positiveCount.addAndGet(1);
            }else if(num < 0){
                //负数
                Thread.sleep(2000);
                negativeCount.addAndGet(1);
            }

            //结果返回
            return num;
        };
    }
}
